package com.csii.config.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

/**
 * 用户认证和授权
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {


    // 授权：验证权限时调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("doGetAuthorizationInfo<<<<<<<<<<<<");
        String username = (String) principalCollection.getPrimaryPrincipal();
        // 当前用户所有角色
        Set<String> roles = new HashSet<>();
        // 当前用户所有权限
        Set<String> permissions = new HashSet<>();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }

    // 认证：登录时调用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userNumber = (String) authenticationToken.getPrincipal();
        String password = "";
        if (authenticationToken.getCredentials()!=null){
            password= new String((char[]) authenticationToken.getCredentials());
        }
        //edit by zhuyc
    	/*Map<String, Object> queryMap = new HashMap<String, Object>();
    	queryMap.put("userNumber", userNumber);

    	SSOUser ssoUser = (SSOUser) sqlMap.queryForObject("sso_user.selectSSOUserByUsername", queryMap);
        System.out.println(ssoUser);
        if (null == ssoUser) {
            throw new UnknownAccountException();
        }
        if (!ssoUser.getPassword().equals(MD5Util.md5(password + ssoUser.getSalt()))) {
            throw new IncorrectCredentialsException();
        }
        password = ShiroKit.md5(password, ssoUser.getUserPasswordSalt());
        authenticationToken = new UsernamePasswordToken(userNumber, password);
        if (!ssoUser.getUserPassword().equals(password)) {
            throw new IncorrectCredentialsException();
        }
        if (ssoUser.getUserStatus().equals("0")) {
            throw new LockedAccountException();
        }*/

        return new SimpleAuthenticationInfo(userNumber, password, getName());
    }
}
